<?php

class Api_AuthController extends Zend_Controller_Action {

    public function init() {
        $this->_helper->viewRenderer->setNoRender(true);
    }

    public function postAction() {
        $data = $this->_request->getPost();
        
        $authAdapter = $this->getAuthAdapter();
        $authAdapter->setIdentity($data['Login'])
                ->setCredential($data['Senha']);

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapter);

        if ($result->isValid()):
            $auth = Zend_Auth::getInstance();
            $auth->setStorage(new Zend_Auth_Storage_Session('API'));
            $dataAuth = $authAdapter->getResultRowObject(null, 'Senha');
            $auth->getStorage()->write($dataAuth);
            echo "Logou";
        else:
            echo "Falhou";
        endif;
    }

    public function getAction(){
        $this->logoutAction();
        #echo "Deslogou!";
    }


    private function getAuthAdapter() {
        $bootstrap = $this->getInvokeArg('bootstrap');
        $resource = $bootstrap->getPluginResource('db');
        $db = $resource->getDbAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
        $authAdapter->setTableName('usuarios')
                ->setIdentityColumn('Login')
                ->setCredentialColumn('Senha');
                #->setCredentialTreatment('Regra <> 0');
        return $authAdapter;
    }

    public function logoutAction() {
        $auth = Zend_Auth::getInstance();
        $auth->setStorage(new Zend_Auth_Storage_Session('API'));
        $auth->clearIdentity();
    }

}

